<template>
  <div class="Box">
    <!-- 顶部搜索 -->
    <div class="SearchBox flex-LAR">
      <el-input v-model="SearchKeyWord.searchValue" placeholder="请输入搜索内容" class="input-with-select">
        <template #prepend>
          <el-select v-model="SearchKeyWord.selectKey" style="width: 6.25rem">
          </el-select>
        </template>
        <template #append>
          <el-button class="searchBtn" :icon="Search" />
        </template>
      </el-input>
      <div>
        <el-button type="success" @click="handleAdd">新增预案</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div class="TableBox">
      <cy-table class="Table" row-key="event_id" :data="tableData" :columns="ruleTable.columns" :loading="loading" />
    </div>
    <!-- 分页 -->
    <div class="PageBox">
      <el-pagination :hide-on-single-page="false" v-model:current-page="page.currentPage" v-model:page-size="page.pageSize"
        v-model:total="page.total" />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预案名称" prop="plan_name">
              <el-input v-model="form.plan_name" placeholder="请输入预案名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预案类型" prop="plan_type">
              <el-select v-model="form.plan_type" placeholder="请选择预案类型">
                <el-option v-for="item in planTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事件等级" prop="event_level">
              <el-select v-model="form.event_level" placeholder="请选择事件等级">
                <el-option v-for="item in eventLevelOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsible_person_id">
              <el-select v-model="form.responsible_person_id" placeholder="请选择负责人">
                <el-option v-for="person in personnelList" :key="person.personnel_id" :label="person.name"
                  :value="person.personnel_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应急团队" prop="responsible_team_id">
              <el-select v-model="form.responsible_team_id" placeholder="请选择应急团队">
                <el-option v-for="team in teamList" :key="team.team_id" :label="team.team_name" :value="team.team_id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effective_date">
              <el-date-picker v-model="form.effective_date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期" prop="expiry_date">
              <el-date-picker v-model="form.expiry_date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="资源需求" prop="resource_requirements">
          <el-input v-model="form.resource_requirements" type="textarea" :rows="3" placeholder="请输入资源需求，JSON格式" />
        </el-form-item>

        <el-form-item label="处置步骤" prop="action_steps">
          <el-input v-model="form.action_steps" type="textarea" :rows="5" placeholder="请输入处置步骤，JSON格式" />
        </el-form-item>

        <el-form-item label="预案内容" prop="plan_content">
          <el-input v-model="form.plan_content" type="textarea" :rows="8" placeholder="请输入详细预案内容" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from "@element-plus/icons-vue";
import CyTable from "@/components/table";

const page = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 12,
});

const SearchKeyWord = reactive({
  selectKey: "预案ID",
  searchValue: "",
});

const tableData = ref([
  {
    plan_id: 1,
    plan_name: '地震应急预案',
    plan_type: 'natural_disaster',
    event_level: '3',
    responsible_person_id: 1,
    responsible_team_id: 1,
    responsible_team: '应急救援一队',
    plan_content: '地震发生后的应急响应流程...',
    resource_requirements: '{"equipment":["生命探测仪","破拆工具"],"personnel":10}',
    action_steps: '[{"step":1,"action":"启动应急响应","time":"立即"},{"step":2,"action":"人员疏散","time":"30分钟内"}]',
    approval_status: 'approved',
    effective_date: '2025-01-01',
    expiry_date: '2024-12-31',
  },
  {
    plan_id: 2,
    plan_name: '疫情应急预案',
    plan_type: 'public_health',
    event_level: '4',
    responsible_person_id: 2,
    responsible_team_id: 2,
    responsible_team: '医疗应急队',
    plan_content: '突发公共卫生事件应急响应...',
    resource_requirements: '{"medical":["防护服","检测试剂"],"quarantine_rooms":5}',
    action_steps: '[{"step":1,"action":"隔离病例","time":"立即"},{"step":2,"action":"区域消杀","time":"2小时内"}]',
    approval_status: 'approved',
    effective_date: '2025-03-20',
    expiry_date: '2023-12-31',
  },
  {
    plan_id: 3,
    plan_name: '火灾应急预案',
    plan_type: 'safety_accident',
    event_level: '2',
    responsible_person_id: 3,
    responsible_team_id: 1,
    responsible_team: '应急救援一队',
    plan_content: '建筑物火灾应急处理流程...',
    resource_requirements: '{"fire_extinguishers":10,"escape_masks":50}',
    action_steps: '[{"step":1,"action":"报警","time":"立即"},{"step":2,"action":"初期灭火","time":"5分钟内"}]',
    approval_status: 'pending',
    effective_date: '2025-03-01',
    expiry_date: null,
  },
  {
    plan_id: 4,
    plan_name: '洪水应急预案',
    plan_type: 'natural_disaster',
    event_level: '3',
    responsible_person_id: 1,
    responsible_team_id: 1,
    responsible_team: '应急救援一队',
    plan_content: '洪水发生后的应急响应流程...',
    resource_requirements: '{"sandbags":100,"rescue_boats":5}',
    action_steps: '[{"step":1,"action":"疏散群众","time":"立即"},{"step":2,"action":"加固堤坝","time":"2小时内"}]',
    approval_status: 'approved',
    effective_date: '2025-03-11',
    expiry_date: '2024-03-31',
  },
  {
    plan_id: 5,
    plan_name: '网络安全应急预案',
    plan_type: 'other',
    event_level: '2',
    responsible_person_id: 2,
    responsible_team_id: 2,
    responsible_team: '技术保障队',
    plan_content: '网络安全事件应急响应流程...',
    resource_requirements: '{"firewalls":5,"antivirus_software":10}',
    action_steps: '[{"step":1,"action":"隔离受感染系统","time":"立即"},{"step":2,"action":"恢复数据","time":"24小时内"}]',
    approval_status: 'pending',
    effective_date: '2025-02-01',
    expiry_date: '2024-04-30',
  },
  {
    plan_id: 6,
    plan_name: '交通事故应急预案',
    plan_type: 'safety_accident',
    event_level: '2',
    responsible_person_id: 3,
    responsible_team_id: 1,
    responsible_team: '应急救援一队',
    plan_content: '交通事故应急处理流程...',
    resource_requirements: '{"first_aid_kits":20,"traffic_cones":50}',
    action_steps: '[{"step":1,"action":"现场警戒","time":"立即"},{"step":2,"action":"伤员救治","time":"30分钟内"}]',
    approval_status: 'approved',
    effective_date: '2025-03-21',
    expiry_date: '2024-06-30',
  },
  {
    plan_id: 7,
    plan_name: '环境污染应急预案',
    plan_type: 'public_health',
    event_level: '3',
    responsible_person_id: 2,
    responsible_team_id: 2,
    responsible_team: '环保应急队',
    plan_content: '环境污染事件应急响应流程...',
    resource_requirements: '{"hazardous_waste_containers":10,"decontamination_kits":5}',
    action_steps: '[{"step":1,"action":"封锁污染区域","time":"立即"},{"step":2,"action":"清理污染","time":"24小时内"}]',
    approval_status: 'pending',
    effective_date: '2025-01-21',
    expiry_date: '2024-07-31',
  },
  {
    plan_id: 8,
    plan_name: '燃气泄漏应急预案',
    plan_type: 'safety_accident',
    event_level: '2',
    responsible_person_id: 1,
    responsible_team_id: 1,
    responsible_team: '应急救援一队',
    plan_content: '燃气泄漏应急处理流程...',
    resource_requirements: '{"gas_detectors":10,"fire_extinguishers":20}',
    action_steps: '[{"step":1,"action":"切断气源","time":"立即"},{"step":2,"action":"疏散人员","time":"15分钟内"}]',
    approval_status: 'approved',
    effective_date: '2025-02-01',
    expiry_date: '2024-08-31',
  },
  {
    plan_id: 9,
    plan_name: '群体性事件应急预案',
    plan_type: 'social_security',
    event_level: '3',
    responsible_person_id: 3,
    responsible_team_id: 1,
    responsible_team: '应急救援一队',
    plan_content: '群体性事件应急响应流程...',
    resource_requirements: '{"riot_gear":20,"negotiators":5}',
    action_steps: '[{"step":1,"action":"现场控制","time":"立即"},{"step":2,"action":"沟通协调","time":"2小时内"}]',
    approval_status: 'pending',
    effective_date: '2025-02-01',
    expiry_date: '2024-09-30',
  },
  {
    plan_id: 10,
    plan_name: '电力故障应急预案',
    plan_type: 'safety_accident',
    event_level: '2',
    responsible_person_id: 2,
    responsible_team_id: 2,
    responsible_team: '技术保障队',
    plan_content: '电力故障应急处理流程...',
    resource_requirements: '{"generators":5,"electrician_tools":10}',
    action_steps: '[{"step":1,"action":"启动备用电源","time":"立即"},{"step":2,"action":"故障排查","time":"2小时内"}]',
    approval_status: 'approved',
    effective_date: '2025-01-01',
    expiry_date: '2024-10-31',
  }
]);

const ruleTable = reactive({
  columns: [
  {
      type: "selection",
      width: 55,
    },
    { prop: "plan_id", label: "预案ID" },
    { prop: "plan_name", label: "预案名称" },
    {
      prop: "plan_type", label: "预案类型",
      render: ({ row }) => (
        <el-tag type={getPlanTypeTag(row.plan_type)}>
          {getPlanTypeName(row.plan_type)}
        </el-tag>
      ),
    },
    {
      prop: "event_level", label: "事件等级",
      render: ({ row }) => (
        <el-tag type={getEventLevelTag(row.event_level)}>
          {getEventLevelName(row.event_level)}
        </el-tag>
      ),
    },
    { prop: "responsible_person_id", label: "负责人",
    render: ({ row }) => (
        <span>
          {getEventPersonnelName(row.responsible_person_id)}
        </span>
      ),
     },
    { prop: "responsible_team", label: "应急团队" },
    {
      prop: "approval_status", label: "状态",
      render: ({ row }) => (
        <el-tag type={getStatusTag(row.approval_status)}>
          {getStatusName(row.approval_status)}
        </el-tag>
      ),
    },
    { prop: "effective_date", label: "生效日期" },
    {
      label: "操作",
      align: "center",
      width:250,
      render: ({ row }) => (
        <div>
          <el-button>查看</el-button>
          <el-button type="primary">编辑</el-button>

          <el-button type="danger">
            删除
          </el-button>
        </div>
      ),
    },
  ],
});

const personnelList = ref([
  { personnel_id: 1, name: '叶致远' },
  { personnel_id: 2, name: '向子韬' },
  { personnel_id: 3, name: '金詩涵' },
  { personnel_id: 4, name: '蒋嘉伦' },
]);

const teamList = ref([
  { team_id: 1, team_name: '应急救援一队' },
  { team_id: 2, team_name: '医疗应急队' }
]);

const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);

const form = reactive({
  plan_id: '',
  plan_name: '',
  plan_type: '',
  event_level: '',
  responsible_person_id: '',
  responsible_team_id: '',
  plan_content: '',
  resource_requirements: '',
  action_steps: '',
  approval_status: 'draft',
  effective_date: '',
  expiry_date: '',
  version: ''
});

const rules = reactive({
  plan_name: [{ required: true, message: '请输入预案名称', trigger: 'blur' }],
  plan_type: [{ required: true, message: '请选择预案类型', trigger: 'change' }],
  event_level: [{ required: true, message: '请选择事件等级', trigger: 'change' }],
  responsible_person_id: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  effective_date: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
});

const planTypeOptions = ref([
  { value: 'natural_disaster', label: '自然灾害' },
  { value: 'public_health', label: '公共卫生' },
  { value: 'safety_accident', label: '安全事故' },
  { value: 'social_security', label: '社会治安' },
  { value: 'other', label: '其他' }
]);

const eventLevelOptions = ref([
  { value: '1', label: '一般' },
  { value: '2', label: '较大' },
  { value: '3', label: '重大' },
  { value: '4', label: '特别重大' }
]);

const statusOptions = ref([
  { value: 'draft', label: '草稿' },
  { value: 'pending', label: '待审' },
  { value: 'approved', label: '已批' },
  { value: 'rejected', label: '已拒' }
]);

const getPlanTypeName = (type) => {
  const item = planTypeOptions.value.find(item => item.value === type);
  return item ? item.label : '未知';
};

const getPlanTypeTag = (type) => {
  const map = {
    natural_disaster: 'danger',
    public_health: 'warning',
    safety_accident: '',
    social_security: 'info',
    other: ''
  };
  return map[type] || '';
};

const getEventLevelName = (level) => {
  const item = eventLevelOptions.value.find(item => item.value === level);
  return item ? item.label : '未知';
};
const getEventPersonnelName = (id) => {
  const item = personnelList.value.find(item => item.personnel_id === id);
  return item ? item.name : '未知';
};

const getEventLevelTag = (level) => {
  const map = {
    '1': '',
    '2': 'warning',
    '3': 'danger',
    '4': 'danger'
  };
  return map[level] || '';
};

const getStatusName = (status) => {
  const item = statusOptions.value.find(item => item.value === status);
  return item ? item.label : '未知';
};

const getStatusTag = (status) => {
  const map = {
    draft: '',
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  };
  return map[status] || '';
};

const handleAdd = () => {
  dialogTitle.value = '新增应急预案';
  formRef.value?.resetFields();
  dialogVisible.value = true;
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.plan_id) {
        const index = tableData.value.findIndex(item => item.plan_id === form.plan_id);
        if (index !== -1) {
          tableData.value[index] = { ...form };
          ElMessage.success('编辑成功');
        }
      } else {
        form.plan_id = tableData.value.length + 1;
        tableData.value.push({ ...form });
        ElMessage.success('新增成功');
      }
      dialogVisible.value = false;
    } else {
      ElMessage.error('表单验证失败');
    }
  });
};
</script>

<style scoped lang="scss">
.Box {
  position: relative;

  .SearchBox {
    width: 100%;
    height: 60px;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    .el-input {
      width: 350px;
      margin-left: 0.5rem;
    }

    .searchBtn {
      color: rgb(15, 153, 245);
    }

    .addBtn {
      margin-right: 1rem;
    }
  }

  .PageBox {
    background-color: #fff;
    padding-left: 30%;
    margin: 1rem;
  }

  .TableBox {
    .Table {
      width: 100%;
      min-height: 25rem;
      border-top: 1px solid #eee;
    }
  }

  .EditForm {
    :deep(.el-form-item__content) {
      display: flex;
      justify-content: center;
      align-content: center;
    }
  }
}
</style>